"""
Description:
"""

from DrissionPage import Chromium
from utils.file_operation import save_dict_to_json, load_json_to_dict
import json

browser = Chromium(9222)

# browser.new_tab("https://www.baidu.com")

# browser.wait(10)

# browser.quit()
 
tab1 = browser.latest_tab


def click_next_page(tab1):
    """点击下一页"""
    # 店铺商品列表状态下的xpath
    # pagination_dom = tab1.ele(
    #     "xpath://*[@id='reactRoot']/div[1]/div/div[2]/div/div/div[2]"
    # )

    # 用户商城搜索页面
    # https://www.rjmart.cn/shop?id=1851
    # pagination_dom = tab1.ele("xpath://*[@class='ZenPagination-wrap']")
    # pagination_dom = tab1.ele(".ZenPagination-wrap")

    # 特殊状态下的xpath
    # pagination_dom = tab1.ele(
    #     "xpath://*[@id='reactRoot']/div[1]/div/div[2]/div[3]/div/div[2]/div[4]"
    # )
    # 选择下一页
    # next_page_dom = pagination_dom.ele(".=zen_page").child(-1)
    next_page_dom = tab1.ele(".zen_page").child(-1)
    # next_page_dom = tab1.ele(".=zen_fs-14 zen_bdr-4 ZenPagination-page ZenPagination-next")

    # pagination_dom = tab1.ele("xpath://*[@id='reactRoot']/div[1]/div/div[2]/div[2]/div/div[2]/div[4]/div/div/span[1]")
    # next_page_dom = pagination_dom.child(-1)
    # 点击下一页
    next_page_dom.click()


def extract_page_data(raw_data: dict) -> list:
    """提取数据，去除不需要的字段"""
    page_data = json.loads(raw_data)
    products = page_data["data"]["products"]
    # 需要删除的字段列表
    remove_keys = [
        "supplierFlag",
        "level",
        "protocol",
        "searchAfter",
        "agencyName",
        "commentCount",
        "reagent100",
        "rs",
        "rh",
        "rsh",
        "deliveryProxyOn",
        "suppDeliveryProxyLabels",
        "topRightImageTag",
        "activityId",
        "rt",
        "concentration",
        "suppVipTag",
        "suppVipLevel",
        "spotTag",
        "orgProtocol",
        "promotionTag",
        "pw",
        "negotiatedPrice",
        "activityPrice",
        "groupBuying",
        "attrItems",
        "carryFeeId",
    ]
    # 针对每个产品，删除不需要的字段
    for item in products:
        for key in remove_keys:
            item.pop(key, None)
    return products


def get_prolist(num):
    data_list = []
    # 监听数据包
    listen_url = "store/athena/search/main"
    tab1.listen.start(listen_url)

    for num in range(num):
        print(f"点击{num+1}次")
        click_next_page(tab1)
        # 等待数据包
        data_packet = tab1.listen.wait()
        # 获取相应jso数据
        resp_data = data_packet.response.raw_body
        data_list.extend(extract_page_data(resp_data))
        # 等待2-3秒
        browser.wait(3, 6)

    save_dict_to_json(data_list, "total_list.json")


def get_prodes(data_list):
    listen_url = "/store/cart/getProductDetail"

    total_num = len(data_list)
    res_list = []

    for item in data_list:
        try:
            tab1.listen.start(listen_url)
            tab1.get(
                f"https://www.rjmart.cn/detail?productId={item['id']}&suppId={item['supplierId']}"
            )
            # 等待数据包
            data_packet = tab1.listen.wait()
            # 获取相应jso数据
            resp_data = data_packet.response.raw_body
            res_list.append(json.loads(resp_data)["data"])
            tab1.listen.stop()
            tab1.wait(2, 5)

        except Exception as e:
            print(e)
            continue

        finally:
            total_num -= 1
            print(f"剩余{total_num}个")

    save_dict_to_json(res_list, "total_list_with_desc.json")


def get_login():
    tab1.get("https://www.rjmart.cn/Login")
    tab1.wait(3)
    tab1.ele(
        "xpath://*[@id='reactRoot']/div[1]/div/div[2]/div[2]/div[2]/div/form/div[3]/div[1]/input"
    ).input("18054211718")
    tab1.ele(
        "xpath://*[@id='reactRoot']/div[1]/div/div[2]/div[2]/div[2]/div/form/div[3]/div[2]/input"
    ).input("zhujie1234")
    tab1.wait(2)
    tab1.ele(
        "xpath://*[@id='reactRoot']/div[1]/div/div[2]/div[2]/div[2]/div/form/div[3]/div[4]/button"
    ).click()


if __name__ == "__main__":
    print("hello")

    # get_login()
    get_prolist(119)

    # data_list = load_json_to_dict("total_list.json")
    # get_prodes(data_list)

    # save_dict_to_json(data_list, "total_list_with_desc.json")
    # get_prolist(48)
